<template>
  <div>
    <!-- 退单详情 -->
    <el-dialog
      v-el-drag-dialog
      title="退货单"
      :visible.sync="visible"
      width="1024px"
      @closed="reset"
    >
      <el-form ref="dataForm" class="form" :model="detailInfo" label-position="right" label-width="100px">
        <el-form-item label="退货单位:" prop="orgName">
          <el-input v-model="detailInfo.orgName" disabled />
        </el-form-item>
        <el-form-item label="退货人:" prop="operatorId">
          <el-select v-model="detailInfo.operatorId" :disabled="type==='detail'" :loading="$loadingPlugin.getOwnersList" style="width: 100%;" placeholder="请选择">
            <el-option
              v-for="item in ownersList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="退货时间:" prop="returnTime">
          <el-input v-model="detailInfo.returnTime" disabled />
        </el-form-item>
        <el-form-item label="关联订单号:" prop="orderCode">
          <el-input v-model="detailInfo.orderCode" disabled />
        </el-form-item>
        <el-form-item label="客户名称:" prop="csmName">
          <el-input v-model="detailInfo.csmName" disabled />
        </el-form-item>
        <el-form-item label="联系电话:" prop="csmPhone">
          <el-input v-model="detailInfo.csmPhone" disabled />
        </el-form-item>
        <el-form-item label="地址:" prop="csmAddress" style="width: 66.6%;">
          <el-input v-model="detailInfo.csmAddress" disabled />
        </el-form-item>
        <el-form-item label="退货原因:" prop="remark" class="block">
          <el-input v-model="detailInfo.remark" disabled />
        </el-form-item>
      </el-form>
      <lb-table
        ref="lbTable"
        class="table"
        border
        highlight-current-row
        element-loading-text="加载中"
        :height="300"
        :column="tableData.column"
        :data="tableData.data"
        :pagination="false"
        :summary-method="getSummaries"
        show-summary
      />
      <div v-if="type==='audit'" slot="footer" class="dialog-footer">
        <el-button :loading="$loadingPlugin.del" type="primary" @click="del">
          作废
        </el-button>
        <el-button :loading="$loadingPlugin.success" type="primary" @click="success">
          通过
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { queryOwnerList, queryReturnGoodsParam, queryReturnGoodsDefaultData, auditReturnGoodsOrder } from '@/api'
  import { mapGetters } from 'vuex'
  import { formatColumnMap } from '@/utils'

  export default {
    name: 'returnOfTheAudit',
    data() {
      return {
        visible: false,
        type: 'detail',
        row: {},
        detailInfo: {
          operatorId: '',
          returnTime: ''
        },
        specList: [],
        ownersList: [],
        tableData: {
          total: 0,
          column: [
            {
              type: 'index'
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 150
            },
            {
              prop: 'specCode',
              label: '规格型号',
              render: (h, { row }) => <span>{ row.specCode && formatColumnMap(this.specList, 'specCode', row.specCode, 'specName') }</span>
            },
            {
              prop: 'goodsCount',
              label: '数量',
              align: 'right'
            },
            {
              prop: 'netWeight',
              label: '净重',
              align: 'right'
            },
            {
              prop: 'price',
              label: '单价',
              align: 'right'
            },
            {
              prop: 'amount',
              label: '退货金额',
              align: 'right',
              render: (h, { row }) => <span>{ row.amount ? (row.amount * 1).toFixed(2) : '' }</span>
            }
          ],
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'corpSettingData'
      ])
    },
    methods: {
      async open(row, type) {
        this.type = type
        await Promise.all([this.getDeaultData(row.orderCode), this.getParams(row.billCode)])
        this.getOwnersList(this.detailInfo.orgId)
        return new Promise((resolve) => {
          this.resolve = resolve
          this.visible = true
          this.row = Object.assign(this.row, row)
        })
      },
      async getDeaultData(orderCode) {
        const res = await queryReturnGoodsDefaultData({ orderCode })
        this.specList = JSON.parse(res.data.specList)
      },
      async getParams(billCode) {
        const res = await queryReturnGoodsParam({ billCode })
        this.detailInfo = res.data.detailInfo
        if (res.data.detailInfo.recycleDetailList) this.tableData.data = res.data.detailInfo.recycleDetailList
      },
      // 查询处理人列表
      async getOwnersList(orgId) {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownersList = res.data
        if (res.data.length > 0) this.detailInfo.operatorId = res.data[0].userId
      },
      // 通过（审核通货单）
      success() {
        const user = this.ownersList.find(item => item.userId === this.detailInfo.operatorId)
        const params = {
          billCode: this.detailInfo.billCode,
          returnTime: this.detailInfo.returnTime,
          operatorId: this.detailInfo.operatorId,
          operator: user.userName,
          recycleDetailList: this.tableData.data
        }
        this.$confirm('确认要审核该退货单吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.submit(params)
        })
      },
      async submit(params) {
        await auditReturnGoodsOrder(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      },
      del() {
        this.$emit('del', this.row)
      },
      // 合计方法
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
            return
          }
          if (column.property === 'netWeight' || column.property === 'price') {
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          }
        })
        return sums
      },
      reset() {
        this.type = 'detail'
        this.detailInfo = {
          operatorId: '',
          returnTime: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 33.3%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
